<template>
  <n-card :bordered="false" class="proCard">
    <div class="table-toolbar">
      <n-button type="primary" @click="addTable">
        <template #icon>
          <n-icon>
            <PlusOutlined />
          </n-icon>
        </template>
        新建
      </n-button>
    </div>
    <n-data-table
      :columns="columns"
      :data="classifyData"
      :row-key="(row) => row.id"
      :cascade="false"
      :scroll-x="1080"
      allow-checking-not-loaded
      @load="onLoad"
    />
    <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" :title="editTitle">
      <n-form
        :model="formParams"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        :label-width="80"
        class="py-4"
      >
        <n-form-item label="分类名称" path="classifyName">
          <n-input placeholder="请输入分类名称" v-model:value="formParams.classifyName" />
        </n-form-item>
        <n-form-item label="分类图片" path="classifyImg">
          <!-- <n-input placeholder="请输入分类图片" v-model:value="formParams.classifyImg" /> -->
          <BasicUpload
            :data="{ scene: 'classify' }"
            name="file"
            :width="100"
            :height="100"
            :maxSize="2"
            :maxNumber="1"
            @uploadChange="uploadChange"
            v-model:value="uploadList"
            helpText="单个文件不超过2MB，最多只能上传1个文件"
          />
        </n-form-item>
        <n-form-item label="上级分类" path="pid">
          <n-tree-select
            :options="editClassifyData"
            key-field="id"
            label-field="classifyName"
            v-model:value="formParams.pid"
            :on-load="handleClassifyLoad"
          />
        </n-form-item>
        <!-- <n-form-item label="是否展示" path="isShow">
          <n-input placeholder="请输入是否展示" v-model:value="formParams.isShow" />
        </n-form-item>
        <n-form-item label="父id" path="pid">
          <n-input placeholder="请输入父id" v-model:value="formParams.pid" />
        </n-form-item>
        <n-form-item label="分类路径0|1|2,便于查询" path="classifyPath">
          <n-input
            placeholder="请输入分类路径0|1|2,便于查询"
            v-model:value="formParams.classifyPath"
          />
        </n-form-item>
        <n-form-item label="是否禁用,0=正常,1=禁用" path="disable">
          <n-input placeholder="请输入是否禁用,0=正常,1=禁用" v-model:value="formParams.disable" />
        </n-form-item> -->
        <n-form-item label="排序" path="sort">
          <n-input-number placeholder="请输入排序" v-model:value="formParams.sort" clearable />
        </n-form-item>
      </n-form>

      <template #action>
        <n-space>
          <n-button @click="() => (showModal = false)">取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmForm">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </n-card>
</template>

<script lang="ts" setup>
  import { h, reactive, ref } from 'vue';
  import { useDialog, useMessage, NButton, NSwitch, TreeSelectOption } from 'naive-ui';
  //import { FormSchema } from '@/components/Form/index';
  import { PlusOutlined } from '@vicons/antd';
  import {
    getGoodsClassifyList,
    saveGoodsClassify,
    updateGoodsClassify,
    deleteGoodsClassify,
    BasicResponseModel,
    updateGoodsClassifyShow,
  } from '@/api/goods/goodsClassify';
  import { ResultEnum } from '@/enums/httpEnum';
  // import { useGlobSetting } from '@/hooks/setting';

  // const globSetting = useGlobSetting();
  // const { uploadUrl } = globSetting;

  const rules = {
    classifyName: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入分类名称',
    },
    classifyImg: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入上传图片',
    },
    isShow: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入是否展示,0=展示,1=隐藏',
    },
  };

  const formRef: any = ref(null);
  const message = useMessage();
  //const actionRef = ref();

  const showModal = ref(false);
  const formBtnLoading = ref(false);
  const checkedGoodsClassifyId = ref(); //当前编辑id
  const isEdit = ref(false); // 弹出框是否为编辑
  const editTitle = ref('');
  const dialog = useDialog();
  const formParams = reactive({
    id: null,
    classifyName: '',
    classifyImg: '',
    isShow: 0,
    pid: 0,
    classifyPath: '',
    disable: 0,
    sort: 0,
  });
  const formParamsBak = { ...formParams };

  const params = ref({});

  // const uploadHeaders = reactive({
  //   platform: 'miniPrograms',
  //   timestamp: new Date().getTime(),
  //   token: 'Q6fFCuhc1vkKn5JNFWaCLf6gRAc5n0LQHd08dSnG4qo=',
  // });

  const uploadList = ref(['']);

  // 分类表格
  const columns = [
    {
      title: 'id',
      key: 'id',
      width: 20,
    },
    {
      title: '分类名称',
      key: 'classifyName',
      width: 100,
    },
    {
      title: '分类图片',
      key: 'classifyImg',
      width: 100,
      render: (data) => {
        return h('img', { src: data.classifyImg, width: '50' });
      },
    },
    {
      title: '用户端展示',
      key: 'isShow',
      width: 100,
      render: (data) => {
        return h(NSwitch, {
          //disabled: true,
          checkedValue: 0,
          uncheckedValue: 1,
          defaultValue: data.isShow,
          onUpdateValue: async (value) => {
            // console.log(data.id);
            // console.log(value);
            await updateGoodsClassifyShow({ id: data.id, isShow: value });
          },
        });
      },
    },
    {
      title: '排序',
      key: 'sort',
      width: 50,
    },
    {
      title: '操作',
      key: 'actions',
      width: 100,
      render(record) {
        return [
          h(
            NButton,
            {
              style: {
                marginRight: '6px',
              },
              size: 'small',
              onClick: handleEdit.bind(null, record),
            },
            { default: () => '编辑' }
          ),
          h(
            NButton,
            {
              size: 'small',
              onClick: handleDelete.bind(null, record),
            },
            { default: () => '删除' }
          ),
        ];
      },
    },
  ];
  // 表格内分类树形数据
  const classifyData = ref([]);

  // 新增/编辑时 展示用的分类数据
  const editClassifyData = ref([
    {
      id: 0,
      classifyName: '顶级分类',
      isLeaf: false,
      children: [],
    },
  ]);

  async function addTable() {
    // 新增前清空表单
    Object.assign(formParams, formParamsBak);
    // 展示上级分类
    const classifyTree = await getGoodsClassifyList({ pid: 0 });
    editClassifyData.value[0].children = classifyTree;
    uploadList.value = [];
    isEdit.value = false;
    showModal.value = true;
    editTitle.value = '新建';
  }

  async function handleEdit(record: Recordable) {
    console.log('点击了编辑', record);
    // 展示上级分类
    const classifyTree = await getGoodsClassifyList({ pid: 0 });
    editClassifyData.value[0].children = classifyTree;
    checkedGoodsClassifyId.value = record.id;
    Object.assign(formParams, record);
    uploadList.value = [record.classifyImg];
    editTitle.value = '编辑';
    showModal.value = true;
    isEdit.value = true;
  }

  // 新建/编辑中 异步加载
  async function handleClassifyLoad(option: TreeSelectOption) {
    // console.log(params);
    console.log(option);
    option.children = await getGoodsClassifyList({ pid: option.id });
  }

  reloadTable();
  // 刷新表格内数据
  async function reloadTable() {
    classifyData.value = await getGoodsClassifyList({ ...params.value });
  }

  // 表格内异步加载
  function onLoad(row: Record<string, unknown>) {
    return new Promise<void>(async (resolve) => {
      row.children = await getGoodsClassifyList({ pid: row.id });
      resolve();
    });
  }

  function confirmForm(e: { preventDefault: () => void }) {
    e.preventDefault();
    formBtnLoading.value = true;
    //console.log('上传图片', uploadList.value);
    formParams.classifyImg = uploadList.value[0];
    formRef.value.validate(async (errors: any) => {
      if (!errors) {
        let response: BasicResponseModel<any>;
        // 如果是编辑
        if (isEdit.value) {
          formParams.id = checkedGoodsClassifyId.value;
          response = await updateGoodsClassify(formParams);
        } else {
          response = await saveGoodsClassify(formParams);
        }
        const { message: msg, code } = response;
        if (code == ResultEnum.SUCCESS) {
          message.success(msg);
          Object.assign(formParams, formParamsBak);
          showModal.value = false;
          reloadTable();
        } else {
          message.error(msg);
        }
      } else {
        message.error('请填写完整信息');
      }
      formBtnLoading.value = false;
    });
  }

  function handleDelete(record: Recordable) {
    console.log('点击了删除', record);
    dialog.info({
      title: '提示',
      content: `您确定想删除吗?`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        const params = { id: record.id };
        const response = await deleteGoodsClassify(params);
        const { message: msg, code } = response;
        if (code == ResultEnum.SUCCESS) {
          message.success(msg);
          reloadTable();
        } else {
          message.error(msg);
        }
      },
      onNegativeClick: () => {
        //message.error('已取消');
      },
    });
  }

  function uploadChange(list: string[]) {
    console.log(list);
  }

  // function handleSubmit(values: Recordable) {
  //   console.log(values);
  //   params.value = values;
  //   reloadTable();
  // }

  // function handleReset(values: Recordable) {
  //   console.log(values);
  // }
</script>

<style lang="less" scoped>
  .table-toolbar {
    display: flex;
    justify-content: space-between;
    padding: 0 0 16px 0;
  }
</style>
